package cn.pugle.base.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author tzp
 * @since 2019/6/20
 */
public class FutureTest {
    public static void main(String[] args) throws Exception {
        test1();
    }

    public static void test1() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletableFuture<Object> future = CompletableFuture.supplyAsync(new Supplier<Object>() {
            @Override
            public Object get() {
                System.out.println(Thread.currentThread() + " run supplier");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return null;
                }
                System.out.println(Thread.currentThread() + " run supplier done");
                return 1;
            }
        }, executorService).thenApplyAsync(new Function<Object, Object>() {
            //一个屎一样的名字 https://stackoverflow.com/a/47489654/5142886
            @Override
            public Object apply(Object o) {
                System.out.println(Thread.currentThread() + " receive " + o);
                return 2;
            }
        });
        System.out.println("end1");
        if (future.get() != null) {//不get, 上面done和receive都来不及执行
            System.out.println("end2");
        }
    }

    public static void test2() throws Exception {
        CompletableFuture<Object> future = CompletableFuture.supplyAsync(new Supplier<Object>() {
            @Override
            public Object get() {
                System.out.println(Thread.currentThread() + " run supplier");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return null;
                }
                System.out.println(Thread.currentThread() + " run supplier done");
                return 1;
            }
        }).thenApply(new Function<Object, Object>() {
            @Override
            public Object apply(Object o) {
                System.out.println("receive " + o);
                return 2;
            }
        });
        System.out.println("end1");
//        if (future.get() != null) {//不get, 上面done和receive都来不及执行
//            System.out.println("end2");
//        }
    }
}
